package cn.omisheep.commons.util;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Iterator;

/**
 * @author zhouxinchen[1269670415@qq.com]
 * @since 1.0.0
 */
public class StringUtils {

    private StringUtils() {
        throw new UnsupportedOperationException();
    }

    /**
     * 格式化字符串<br>
     * 此方法只是简单将指定占位符 按照顺序替换为参数<br>
     * 如果想输出占位符使用 \\转义即可，如果想输出占位符之前的 \ 使用双转义符 \\\\ 即可<br>
     * 例：<br>
     * 通常使用：format("this is {} for {}", "{}", "a", "b") =》 this is a for b<br>
     * 转义{}： format("this is \\{} for {}", "{}", "a", "b") =》 this is {} for a<br>
     * 转义\： format("this is \\\\{} for {}", "{}", "a", "b") =》 this is \a for b<br>
     *
     * @param formatMsg 字符串模板
     * @param args      参数列表
     * @return 结果
     */
    public static String format(String formatMsg,
                                Object... args) {
        StringBuilder    sb       = new StringBuilder();
        Iterator<Object> iterator = Arrays.stream(args).iterator();
        for (int i = 0; i < formatMsg.length(); ) {
            int _end = formatMsg.indexOf("{}", i);
            if (_end == -1) {
                sb.append(formatMsg, i, formatMsg.length());
                break;
            } else {
                if (iterator.hasNext()) {
                    sb.append(formatMsg, i, _end).append(iterator.next());
                    i = _end + 2;
                } else {
                    sb.append(formatMsg, i, formatMsg.length());
                    break;
                }
            }
        }
        return sb.toString();
    }

    public static boolean hasText(String str) {
        return str != null && !str.isEmpty() && containsText(str);
    }

    private static boolean containsText(CharSequence str) {
        int strLen = str.length();

        for (int i = 0; i < strLen; ++i) {
            if (!Character.isWhitespace(str.charAt(i))) {
                return true;
            }
        }

        return false;
    }

    public static boolean isEmpty(CharSequence str) {
        return str == null || "".contentEquals(str);
    }

    private static final byte[] HEX_ARRAY = "0123456789ABCDEF".getBytes(StandardCharsets.US_ASCII);

    /**
     * byte[] 转化为16进制字符串输出
     *
     * @param bytes 字节数组
     * @return 16进制字符串
     * @since 1.0.5
     */
    public static String bytesToHexStr(byte[] bytes) {
        byte[] hexChars = new byte[bytes.length * 2];

        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;

            hexChars[j * 2]     = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }

        return new String(hexChars, StandardCharsets.UTF_8);
    }
    
}
